package todo;

import se.lth.cs.realtime.PeriodicThread;
import se.lth.cs.realtime.RTThread;
import se.lth.cs.realtime.event.RTEvent;
import done.AbstractWashingMachine;

public class WaterController extends PeriodicThread {

	private AbstractWashingMachine machine;
	private WaterEvent last_event;
	private boolean stable;

	public WaterController(AbstractWashingMachine mach) {
		super(Sim.time(1000));
		this.machine = mach;
	}

	public void perform() {
		while (!mailbox.isEmpty()) {
			last_event = (WaterEvent)mailbox.doFetch();
		}
		
		if (last_event==null) return;
		
		switch (last_event.getMode()) {
		case (WaterEvent.WATER_DRAIN):
			if (machine.getWaterLevel() != 0) {
				machine.setDrain(true);
				stable=false;
			} else if (!stable) {
				machine.setDrain(false);
				((RTThread)last_event.getSource()).putEvent(new AckEvent(this));
				stable=true;
			}
		
			break;
			
		case (WaterEvent.WATER_FILL):
			if (machine.getWaterLevel() < last_event.getLevel()) {
				machine.setFill(true);
				stable=false;
			} else if (!stable) {
				stable=true;
				machine.setFill(false);
				((RTThread)last_event.getSource()).putEvent(new AckEvent(this));
			}
			break;
			
		case (WaterEvent.WATER_IDLE):
			machine.setFill(false);
			machine.setDrain(false);
			
		}
		
	}
}
